package com.kfgj.hkp.common.user.dao.impl;

import com.kfgj.hkp.common.dataaccess.redis.AbstractRedisDao;
import com.kfgj.hkp.common.user.dao.IBaseUserRedisDao;
import com.kfgj.hkp.common.user.entity.BaseUserEntity;

import java.util.concurrent.TimeUnit;

/**
 * Created by liwensihan on 2018/5/18.
 */
public abstract class AbstractBaseUserRedisDao<T extends BaseUserEntity> extends AbstractRedisDao<T> implements IBaseUserRedisDao<T> {

    public abstract String createUserCodeKey(String userCode);

    public abstract String createAuthKey(String authKey);

    @Override
    public String getLoginUserCode(String authKey) {

        return valueOps.get(createAuthKey(authKey));
    }

    @Override
    public void setLoginUserCode(String authKey, String userCode) {
        valueOps.set(createAuthKey(authKey),userCode);
    }

    @Override
    public void setUserInfo(String userCode, T user) {
        try {

            this.saveEntity(createUserCodeKey(userCode),user);

        } catch (Exception e) {

            logger.error("saveUser error ",e);
        }
    }

    @Override
    public T getUserInfo(String userCode) {

        try {
            return this.parseEntity(createUserCodeKey(userCode));
        } catch (Exception e) {
            logger.error("findUserByUserCode from redis error",e);
            return null;
        }

    }

    public void updateAuthKeyExpire(String authKey,long expire){

        if (expire > 0){
//            Calendar cal = Calendar.getInstance();
//            long times = cal.getTimeInMillis() + (expire * 1000);
//            cal.setTimeInMillis(times);
//            template.expireAt(createAuthKey(authKey), cal.getTime());
            template.expire(createAuthKey(authKey),expire, TimeUnit.SECONDS);
        }
    }

    @Override
    public void deleteAuthKey(String authKey) {

        template.delete(createAuthKey(authKey));

    }
}
